﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entities;
using Logic;
using VotanetWebSite.Classes;

namespace VotanetWebSite.Acceso_Votante
{
    public partial class Procesar_Voto : System.Web.UI.Page
    {
        private readonly string USER_MAIL = ConfigurationManager.AppSettings["USER"].ToString();
        private readonly string USER_PASSWORD = ConfigurationManager.AppSettings["PASSWORD"].ToString();
        private readonly string MAIL_SERVER = ConfigurationManager.AppSettings["MAIL_SERVER_NAME"].ToString();
        private readonly string KEY = ConfigurationManager.AppSettings["KEY"].ToString();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (PreviousPage != null && GetVoteSession() != null && Context.Items["Identificador"] != null)
                {
                    GetNameVoter();
                    Dictionary<string, string> tempDic = DecryptDictionary();
                    if (tempDic != null)
                    {
                        Dictionary<string, Candidate> dicCandidato = new Dictionary<string, Candidate>();
                        foreach (KeyValuePair<string, string> item in tempDic)
                        {
                            if (item.Value.Contains("Blanco"))
                            {
                                dicCandidato.Add(item.Value, LoadWhiteCandidate(item.Key));
                            }
                            else
                            {
                                dicCandidato.Add(item.Value, LoadCandidate(item.Value, item.Key));
                            }
                        }

                        Session["dicCandidato"] = dicCandidato;
                    }
                    else
                    {
                        Response.RedirectPermanent("~/Seguridad/Logout.aspx");
                    }
                }
                else
                {
                    Response.RedirectPermanent("~/Seguridad/Logout.aspx");
                }
            }
        }

        protected Voter GetVoteSession()
        {
            return Session["Voter"] as Voter;
        }

        protected Dictionary<string, string> DecryptDictionary()
        {
            return new VotingLogic().DecryptDictionaryLogic((Dictionary<string, string>)Context.Items["Identificador"], KEY);
        }

        protected void GetNameVoter()
        {
            lblNombreVotanteLogin.Text = GetVoteSession().GetFullName();
        }

        protected Candidate LoadCandidate(string id, string office)
        {
            VotingLogic votingLogic = new VotingLogic();
            Candidate candidate = votingLogic.GetCandidateByIdLogic(id, KEY, true);
            Panel panel = new Panel();
            panel.CssClass = "bordeRedondo";

            Panel headerPanel = new Panel();
            headerPanel.CssClass = "encabezado";
            headerPanel.Controls.Add(CreateControl.OfTypeLabel("lblMenu" + office, "Cargo " + office, "label12"));
            panel.Controls.Add(headerPanel);

            if (candidate != null)
            {
                panel.Controls.Add(CreateControl.OfTypeLabel("lblNombre" + candidate.GetFullName(), "Usted ha seleccionado al candidato :" + candidate.GetFullName() + "</br>", "label12"));
                panel.Controls.Add(CreateControl.OfTypeImagen("CandidateImage" + candidate.GetFullName(), candidate.pictureString, @"~/Images/CandidateImage/"));
            }
            else
            {
                Response.RedirectPermanent("~/Seguridad/Logout.aspx");
            }
            PanelCandidato.Controls.Add(panel);
            return candidate;

        }

        protected Candidate LoadWhiteCandidate(string office)
        {
            Panel panel = new Panel();
            panel.CssClass = "bordeRedondo";
            Panel headerPanel = new Panel();
            headerPanel.CssClass = "encabezado";
            headerPanel.Controls.Add(CreateControl.OfTypeLabel("lblMenu" + office, "Cargo " + office, "label12"));
            panel.Controls.Add(headerPanel);
            panel.Controls.Add(CreateControl.OfTypeLabel("lblVotBlanco" + office, "Usted ha votado en blanco .</br>", "label12"));
            panel.Controls.Add(CreateControl.OfTypeImagen("imagenBlanco" + office, "VotoBlanco.jpg", @"~/Images/"));
            PanelCandidato.Controls.Add(panel);

            Candidate c = new Candidate();
            c.votingId = Convert.ToInt32(new VotingLogic().DecryptLogic(Session["VotingID"].ToString(), KEY));
            return c;
        }

        protected void BtnAtras_Click(object sender, EventArgs e)
        {
            Response.RedirectPermanent("Sufragio_Votante.aspx");
            ///TODO   eliminar las sessiones !! PPPP
        }

        protected void BtnConfirmar_Click(object sender, EventArgs e)
        {
            ConfirmVote();
        }

        protected void BtnLogout_Click(object sender, ImageClickEventArgs e)
        {
            Response.RedirectPermanent("~/Seguridad/Logout.aspx");
        }

        protected void ConfirmVote()
        {
            VotingLogic votingLogic = new VotingLogic();
            Dictionary<string, Candidate> candidateDictionary = Session["dicCandidato"] as Dictionary<string, Candidate>;

            if (candidateDictionary != null)
            {
                InsertCandidate(votingLogic, candidateDictionary.Values.ToList());
            }
            else
            {
                Response.RedirectPermanent("~/Seguridad/Logout.aspx");
            }
        }

        protected void InsertCandidate(VotingLogic votingLogic, List<Candidate> candidateList)
        {
            VoterLogic voterLogic = new VoterLogic();
            Voter voter = GetVoteSession();
            voter.voucherVotingId = voterLogic.GeneratePasswordPdf();
            voter.picturePath = "~/App_Data/BackupPDF/RespaldoVoto" + voter.name + voter.lastName + "_" + voter.voucherVotingId + ".pdf";

            if (votingLogic.InsertarCandidatoLogica(candidateList, voter))
            {
                voterLogic.GeneratePdfLogic(voter);
                voterLogic.SendEmailLogic(voter, "Su voto ha sido ingresado ", USER_MAIL, USER_PASSWORD, MAIL_SERVER, HttpContext.Current.Server.MapPath(voter.picturePath));
                InsertStatistic(candidateList);

                Context.Items.Add("message", "1");
                Server.Transfer("~/Seguridad/Logout.aspx", false);
            }
            else
            {
                Context.Items.Add("message", "2");
                Server.Transfer("~/Seguridad/Logout.aspx", false);
            }
        }

        protected void InsertStatistic(List<Candidate> candidateList)
        {
            new StatisticLogic().InsertStatisticLogic(candidateList, GetVoteSession(), Session["VotingID"], KEY);
        }

    }
}